import os
import sys
import time

cur_path = os.path.dirname(os.path.abspath(__file__))
root_path = os.path.dirname(cur_path)
sys.path.append(root_path)

from common.logger import Log
from utils.utils import Utils
from framework.controller import Controller
from framework.cmd_parser import CmdParser
from framework.config_parser import ConfigFileParser
from framework.options_combiner import OptionCombiner
from common.benchmark_var import GlobalEnv, GlobalVar, ConfigOptions as Ops, ConfigSections as Sections
from common.machine_info import MachineInfo


def prepare_env():
    version_txt = os.path.join(GlobalEnv.GCBS_ROOT_DIR, 'version.txt')
    with open(version_txt) as version_file:
        GlobalVar.VERSION = version_file.read().strip()


if __name__ == '__main__':
    prepare_env()
    Utils.validate_dependence()

    # get run start time
    run_time = time.time()

    machine_info = MachineInfo()
    machine_info.get_machine_info()
    machine_info.make_machine_info_file()

    cmd_parser = CmdParser()
    cmd_options = cmd_parser.parse()
    config_parser = ConfigFileParser()
    ini_options = config_parser.parse_ini(cmd_parser.get_config_file())
    # final run args
    combiner = OptionCombiner()
    options = combiner.combine_options(ini_options, cmd_options)
    Log().set_log_level(options.get(Sections.GENERAL).get(Ops.DEBUG))

    if not options.get(Sections.GENERAL).get(Ops.SKIP_VERIFY):
        Utils.validate_files()

    controller = Controller(options, machine_info, run_time)
    controller.execute_benchmark()
